package momo.app.structure;

public class StabRecord
{
	static final double INIT_STABILITY = 1;
	static final double INIT_AVG_SESSION = 1;
	
	private long timeJoined;
	private double duration; //in mins
	private double avgSession;
	private double stability;
	private double activeStability;
	
	public StabRecord(double duration, double stability, double avgSession)
	{
		this.timeJoined = 0;
		this.duration = duration;
		this.stability = stability;
		this.avgSession = avgSession;
		this.activeStability = stability;
	}
	
	public StabRecord(double duration)
	{
		this(duration, INIT_STABILITY, INIT_AVG_SESSION);
	}
	
	public void noteTimeJoined()
	{
		this.timeJoined = System.currentTimeMillis();
	}
	
	private void calculateDuration()
	{
		int calculation = (int)((System.currentTimeMillis() - timeJoined) / 1000);
		calculation = calculation<=0?1:calculation;
		this.duration += (double)calculation/60.0;
	}
	
	private void calculateAvgSession()
	{
//		StringBuffer buffer = new StringBuffer("\n@@@@@@@@@@@@@@@@@@@@@@@");
//		buffer.append("\ncalculateAvgSession");
//		buffer.append("\nBe4 avgSession: " + avgSession);
//		buffer.append("\nduration: " + duration);
		
		this.avgSession = this.avgSession * 0.8 + this.duration * 0.2;
		
//		buffer.append("\nAfter avgSession: " + avgSession);
//		buffer.append("\n@@@@@@@@@@@@@@@@@@@@@@@\n");
//		FileOutput.getInstance().logToFile("stability.log", buffer.toString());
	}
	
	private void calculateActiveStability()
	{
		this.activeStability = 1.0 / (this.avgSession * 0.8 + this.duration * 0.2);
		
//		StringBuffer buffer = new StringBuffer("\n@@@@@@@@@@@@@@@@@@@@@@@");
//		buffer.append("\ncalculateActiveStability");
//		buffer.append("\navgSession: " + avgSession);
//		buffer.append("\nduration: " + duration);
//		buffer.append("\nactiveStability: " + activeStability);
//		buffer.append("\n@@@@@@@@@@@@@@@@@@@@@@@\n");
		
//		FileOutput.getInstance().logToFile("stability.log", buffer.toString());
	}
	
	private void calculateStability()
	{
		this.stability = 1.0 / this.avgSession;
	}
	
	public void resetDurationCal()
	{
		calculateDuration();
		this.noteTimeJoined();
	}
	
	public void reconstruct()
	{
		resetDurationCal();
//		calculateAvgSession();
		calculateActiveStability();
	}
	
	public void leave()
	{
		calculateDuration();
		calculateAvgSession();
		calculateStability();
		this.timeJoined = 0;
		this.duration = 0;
	}
	
	public double getActiveStability()
	{
		return activeStability;
	}
	
	public double getStability()
	{
		return stability;
	}
	
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();
		buffer.append(duration);
		buffer.append(",");
		buffer.append(stability);
		buffer.append(",");
		buffer.append(avgSession);
		buffer.append(",");
		buffer.append(activeStability);
		return buffer.toString();
	}
}//end of class StabRecord
